package com.culturalCenter.dataCenter.service.impl.activity;

import cn.hutool.core.util.StrUtil;
import com.culturalCenter.dataCenter.customEntity.responseParam.activity.ActivityAudienceResponse;
import com.culturalCenter.dataCenter.entity.activity.ActivityAge;
import com.culturalCenter.dataCenter.entity.activity.ActivityAudienceCount;
import com.culturalCenter.dataCenter.mapper.activity.ActivityAgeMapper;
import com.culturalCenter.dataCenter.mapper.activity.ActivityAudienceCountMapper;
import com.culturalCenter.dataCenter.service.activity.ActivityAudienceService;
import org.apache.commons.collections.CollectionUtils;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.text.DecimalFormat;
import java.util.List;

/**
 * @author : weicai
 * @date : 17:04 2020/11/4
 */
@Service
public class ActivityAudienceServiceImpl implements ActivityAudienceService {

    @Resource
    private ActivityAudienceCountMapper activityAudienceCountMapper;
    @Resource
    private ActivityAgeMapper activityAgeMapper;

    @Override
    public ActivityAudienceResponse getAudienceAnalysis(String activityId) {
        ActivityAudienceResponse activityAudienceResponse = new ActivityAudienceResponse();
        //性别统计
        List<ActivityAudienceCount> genderList = activityAudienceCountMapper.queryByActivityId(activityId);
        if (CollectionUtils.isNotEmpty(genderList)) {
            activityAudienceResponse.setGenderList(genderList);
        }
        //年龄统计
        List<ActivityAge> ageIntervalList = activityAgeMapper.queryByActivityId(activityId);
        if (CollectionUtils.isNotEmpty(ageIntervalList)) {
            ageIntervalList.forEach(ageInterval -> {
                if (StrUtil.isNotEmpty(ageInterval.getGeneration())) {
                    int startAge = Integer.parseInt(ageInterval.getGeneration().substring(0, 2));
                    ageInterval.setStartAge(startAge);
                    ageInterval.setEndAge(ageInterval.getGeneration().equals("60以上") ? 120 : Integer.parseInt(ageInterval.getGeneration().substring(3)));
                }
                int sum = ageIntervalList.stream().mapToInt(w -> w.getSignUpNum()).sum();
                if (sum == 0) {
                    ageInterval.setPercentageRate("0.00");
                } else {
                    //计算各个年龄区间的比例
                    DecimalFormat df = new DecimalFormat("0.00");
                    Double percentage = (double) (ageInterval.getSignUpNum()) / sum * 100;
                    ageInterval.setPercentageRate(df.format(percentage));
                }
            });
            activityAudienceResponse.setAgeIntervalList(ageIntervalList);
        }
        return activityAudienceResponse;
    }

}
